package com.pachiraframework.springcloud.async.task;

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.pachiraframework.springcloud.async.utils.SessionUtils;


//起的一个服务
@ServerEndpoint(value = "/websocket/{clientId}")
@Component
public class WebSocketService {

	//静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    
	private Logger logger = Logger.getLogger(WebSocketService.class);

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("clientId") String clientId) {
        this.session = session;
        
		if (SessionUtils.hasConnection(clientId)) {
			logger.info("已经有链接了");
			try {
				SessionUtils.get(clientId).close();
			} catch (Exception e) {
			}
		}
		SessionUtils.put(clientId, session);
        addOnlineCount();           //在线数加1
//        logger.info("有新连接加入！当前在线人数为" + getOnlineCount());
        try {
            sendMessage("发送成功!!");
        } catch (IOException e) {
        	logger.info("IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("clientId") String clientId) {
        subOnlineCount();           //在线数减1
        SessionUtils.remove(clientId);
//        logger.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }


    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
//    	logger.info("发生错误");
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }


    public void sendMessage(String message, Session session) throws IOException{//这个方法来启动服务
    	logger.info("webSocket 开始发送数据:"+message);
    	this.session=session;
    	sendMessage(message);
    }



    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
    	WebSocketService.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
    	WebSocketService.onlineCount--;
    }
	
	
	
	
	
}
